<template>
  <el-dialog
    title="选择分类"
    :visible.sync="searchClassifyModal"
    :modal-append-to-body="false"
    width="60%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleCloseDialog"
  >
    <el-card>
      <div class="search">
        <el-row :gutter="20">
          <el-col :span="16">
            <el-input
              v-model="searchCategoryName"
              search
              enter-button="搜索"
              placeholder="请输入要搜索的分类名称"
            />
          </el-col>
          <el-col :span="8">
            <el-button type="primary" @click="handleSearchCatogray">搜索</el-button>
          </el-col>
        </el-row>
      </div>
      <div class="release">您当前的选择是：{{ categoryFullPathName }}</div>
      <div class="Selectiveclassification">
        <el-row :gutter="24">
          <el-col v-bind="classifyGrid">
            <div class="qw-classify">
              <el-menu width="auto" @select="handleSelectFirstMenu">
                <el-menuItem
                  :index="item.nowTime"
                  v-for="(item, index) in firstMenuList"
                  :key="index"
                >
                  {{ item.categoryName }}
                  <i class="el-icon-arrow-right" />
                </el-menuItem>
              </el-menu>
            </div>
          </el-col>
          <el-col v-bind="classifyGrid">
            <div class="qw-classify">
              <el-menu width="auto" @select="handleSelectSecondMenu">
                <el-menuItem
                  :index="item.nowTime"
                  v-for="(item, index) in secondMenuList"
                  :key="index"
                >
                  {{ item.categoryName }}
                  <i class="el-icon-arrow-right" />
                </el-menuItem>
              </el-menu>
            </div>
          </el-col>
          <el-col v-bind="classifyGrid">
            <div class="qw-classify">
              <el-menu width="auto" @select="handleSelectThirdMenu">
                <el-menuItem
                  :index="item.nowTime"
                  v-for="(item, index) in thirdMenuList"
                  :key="index"
                >
                  {{ item.categoryName }}
                  <i class="el-icon-arrow-right" />
                </el-menuItem>
              </el-menu>
            </div>
          </el-col>
          <el-col v-bind="classifyGrid">
            <div class="qw-classify">
              <el-menu width="auto" @select="handleSelectFourthMenu">
                <el-menuItem
                  :index="item.nowTime"
                  v-for="(item, index) in fourthMenuList"
                  :key="index"
                >
                  {{ item.categoryName }}
                  <i class="el-icon-arrow-right" />
                </el-menuItem>
              </el-menu>
            </div>
          </el-col>
        </el-row>
        <Spin size="large" fix v-if="spinShow"></Spin>
      </div>
      <div class="qw-searchresult" v-if="isShowResults">
        <div class="qw-search-title">
          <span class="title">搜索结果如下：</span>
          <el-button
            class="close_search_result_btn"
            type="text"
            icon="el-icon-close"
            @click="handleCloseCategoryRadioGroup"
            >关闭</el-button
          >
        </div>
        <div class="qw-search-body">
          <el-radio-group
            v-if="searchData.length > 0"
            v-model="categoryUuid"
            vertical
            @change="handleChooseCategoryItem(categoryUuid)"
          >
            <el-radio
              :label="item.categoryUuid"
              v-for="(item, index) in searchData"
              :key="index"
            >
              <span>{{ item.categoryPath }}</span>
            </el-radio>
          </el-radio-group>
          <div class="qw-searchno" v-else>未找到相关分类~~</div>
        </div>
      </div>
    </el-card>
    <!-- 隐藏默认的确定和取消按钮 -->
    <div slot="footer"></div>
  </el-dialog>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { getBtnsId } from '@/libs/btnsPermission';
import { mapMutations } from 'vuex';
export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    }
  },
  data () {
    return {
      spinShow: false,
      searchClassifyModal: this.visible,
      classifyGrid: {
        xl: 6,
        lg: 6,
        md: 6,
        sm: 24,
        xs: 24
      },
      categoryUuid: '', // 当前选择的分类的uuid
      categoryFullPathName: '', // 分类全路径名称
      searchData: [], // 搜索分类名称获取到的分类集合
      searchCategoryName: '', // 搜索分类输入的内容
      isShowResults: false, // 输入搜索内容后的展示区开关
      catograyLevel: '0', // 分类级别
      firstMenuList: [], // 一级分类菜单
      secondMenuList: [], // 二级分类菜单
      thirdMenuList: [], // 三级分类菜单
      fourthMenuList: [], // 四级分类菜单
      /* levelToListName - 用来区别是哪一级别的category */
      levelToListName: new Map([
        [1, 'firstMenuList'],
        [2, 'secondMenuList'],
        [3, 'thirdMenuList'],
        [4, 'fourthMenuList']
      ]),
      nowTime: '',
      categoryUuidIsChange: false
    };
  },
  watch: {
    visible (val) {
      this.searchClassifyModal = val;
      !val || this.clearDataFn();
    }
  },
  methods: {
    ...mapMutations('commonComps/spuAssociatedModal', ['CLEAR_GOODS']),
    handleCloseDialog () {
      this.searchClassifyModal = false
      this.$emit('update:visible', this.searchClassifyModal)
    },
    /* 分类弹框确定方法 */
    handleMakeSureChoose () {
      let categoryData = {
        categoryUuid: this.categoryUuid,
        categoryName: this.categoryFullPathName
      };
      !this.categoryUuidIsChange || this.CLEAR_GOODS();
      this.$emit('getCategoryData', categoryData);
      this.$emit('update:visible', false);
      this.categoryUuidIsChange = false;
    },
    /* 清除一些内容的方法 */
    clearDataFn () {
      this.searchData = [];
      this.searchCategoryName = '';
      this.isShowResults = false;
    },
    /* 分类弹框取消方法 */
    handleCancelChoose () {
      this.$emit('update:visible', false);
    },
    /* 分类弹框的搜索方法 */
    handleSearchCatogray () {
      if (!this.searchCategoryName) {
        this.$message.warning('请输入需要搜索的分类名称!');
        return false;
      }
      this.secondMenuList = [];
      this.thirdMenuList = [];
      this.fourthMenuList = [];
      let data = { key: this.searchCategoryName };
      // 开始请求列表
      ApiRequest(
        '/sysback/choose/category/getCategoryListByKey',
        'post',
        data,
        true
      ).then((res) => {
        if (res.retStatus === '1') {
          this.searchData = res.retData;
        }
        this.isShowResults = this.isShowResults || true;
      });
    },
    /* 分类弹框搜索后点击选择展示区radio的方法 */
    handleChooseCategoryItem (categoryUuid) {
      this.categoryUuid = categoryUuid;
      this.categoryFullPathName = this.searchData.reduce((value, item) => {
        if (item.categoryUuid === categoryUuid) {
          value = item.categoryPath.split('>').pop();
        }
        return value;
      }, '');
      this.categoryUuidIsChange = true;
      this.handleMakeSureChoose();
    },
    /* 关闭类弹框搜索后点击选择展示区的方法 */
    handleCloseCategoryRadioGroup () {
      this.isShowResults = false;
      this.categoryUuid = '';
      this.categoryFullPathName = '';
    },
    /* 分类请求方法 */
    requestCategoryAction (params) {
      let { url, type, data, level, nextLevel } = params;
      this.spinShow = true
      ApiRequest(url, type, data, true)
        .then((res) => {
          this.spinShow = false
          if (res.retStatus === '1') {
            switch (level) {
              case '1':
                this.secondMenuList = [];
                this.thirdMenuList = [];
                this.fourthMenuList = [];
                break;
              case '2':
                this.thirdMenuList = [];
                this.fourthMenuList = [];
                break;
              case '3':
                this.fourthMenuList = [];
                break;
              default:
                break;
            }
            let initLevelData = [
              {
                categoryName: '暂无相关分类',
                levelNum: level
              }
            ];
            let retData =
              res.retData.length === 0 ? initLevelData : res.retData;
            if (nextLevel <= 5) {
              retData.forEach((element) => {
                element.nowTime = `${element.categoryUuid || ''},${
                  this.nowTime
                }`;
              });
              this.$data[this.levelToListName.get(nextLevel)] = retData; // 根据level去映射对应的levelData
              this.lastLevel = res.retData.length === 0 || false;
            }
            if (level === '4') {
              this.handleMakeSureChoose();
            }
          }
        })
        .catch(() => {
          this.spinShow = false;
        });
    },
    /* 获取一级分类列表 */
    async getLevelOneCategoryListAction (level = this.catograyLevel) {
      let nextLevel = 1;
      let curBtnId = getBtnsId('关联-查询');
      sessionStorage.setItem('buttonId', curBtnId);
      // 开始请求列表
      await this.requestCategoryAction({
        url: '/sysback/choose/category/getLevelOneCategoryList',
        type: 'post',
        data: {},
        level,
        nextLevel
      });
      this.nowTime = new Date().toLocaleString();
    },
    /* 获取分类路径全名称 */
    getSubCategoryAction (level = this.catograyLevel) {
      let nextLevel = Number(level) + 1;
      let data = {
        parentUuid: this.categoryUuid
      };
      if (!this.categoryUuid) {
        return;
      }
      // 开始请求列表
      this.requestCategoryAction({
        url: '/sysback/choose/category/getByParentUuid',
        type: 'post',
        data,
        level,
        nextLevel
      });
    },
    /* 选择一级分类的 */
    handleSelectFirstMenu (uuidTimeStr) {
      let uuid = uuidTimeStr.split(',')[0];
      this.catograyLevel = '1';
      this.categoryUuid = uuid;
      this.getSubCategoryAction('1');
    },
    /* 选中二级分类 */
    handleSelectSecondMenu (uuidTimeStr) {
      let uuid = uuidTimeStr.split(',')[0];
      this.catograyLevel = '2';
      this.categoryUuid = uuid;
      this.getSubCategoryAction('2');
    },
    /* 选中三级分类 */
    handleSelectThirdMenu (uuidTimeStr) {
      let uuid = uuidTimeStr.split(',')[0];
      this.catograyLevel = '3';
      this.categoryUuid = uuid;
      this.getSubCategoryAction('3');
    },
    /* 选中四级分类 */
    handleSelectFourthMenu (uuidTimeStr) {
      let uuid = uuidTimeStr.split(',')[0];
      this.catograyLevel = '4';
      this.categoryUuid = uuid;
      this.fourthMenuList.forEach((element) => {
        if (element.categoryUuid === uuid) {
          this.categoryFullPathName = element.categoryName;
        }
      });
      this.categoryUuidIsChange = true;
      this.getSubCategoryAction('4');
    }
  }
};
</script>
<style lang="less" scoped>
.qw-classify {
  height: 300px;
  overflow-y: auto;
  border: 1px solid #eeeeee;
}

.qw-search-title {
  display: flex;
  background: #fbfafa;
  justify-items: center;
  align-items: center;
  height: 40px;
  line-height: 40px;
  padding: 0 0 0 10px;
  .title {
    flex: 1;
  }
}
.qw-searchno {
  padding: 16px;
}
.search {
  width: 100%;
  padding: 10px;
  background: #eaf7f9;
}

/deep/ .el-menu-item {
  height: 40px;
  line-height: 40px;
}
.close_search_result_btn {
  padding: 0 10px;
}
/deep/ .el-radio {
  width: 100%;
  height: 50px;
  line-height: 50px;
  padding: 0 16px;
  border-bottom: 1px solid #eee;
}
</style>
